// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import { setTitle, getLocal, setSession, getSession } from '@/utils/navigation'
import { isTrue } from '@/utils/tools'
import NProgress from 'nprogress' // 页面进度条
import 'nprogress/nprogress.css'
import $store from '@/store'
import { loginRouteName, projectName } from '@/app.config'
const routes = [
    {
        path: '/',
        name: 'home',
        redirect: '/Home',
        component: () => import('../views/home/Main.vue'),
        children: [
            {
                path: 'Home',
                name: 'Home',
                meta: {
                    title: 'Home',
                    affix: true,
                },
                component: () => import('@/views/Home.vue'),
            },{
                path: '/about',
                name: 'about',
                // 路由级代码拆分
                // 这会为这个路由生成一个单独的块 (about.[hash].js)
                component: () => import('../views/about.vue')
            }]
    },
]

const router = createRouter({
    base: projectName,
    history: createWebHistory(),
    routes
})

const LOGIN_PAGE_ROUTE_NAME = loginRouteName

const linkTo = (to, access, next) => {
    // if (canTurnTo(to.name, access, routers)) next() // 有权限，可访问
    // else next({ replace: true, name: 'error_401' }) // 无权限，重定向到401页面
    // todo 权限
    next()
}

router.beforeEach((to, from, next) => {
    // ------UPM逻辑开始-------
    if (!isTrue(getSession('permission'))) {
        $store.commit('setPermission', 'yes')
    }
    let needUPMList = [
        'CityPrediction',
        'CityDiagnosisWeek',
        'CityDiagnosisIndex',
        'CitySimulation',
    ]
    let url = location.origin
    let needUPM = false
    // ||
    // url.indexOf('lego-test') > -1
    //   ||
    //   url.indexOf('localhost') > -1
    if (url.indexOf('test') > -1 || url.indexOf('test2') > -1) {
        for (let item of needUPMList) {
            if (to.path.indexOf(item) > -1) {
                needUPM = true
            }
        }
    }
    if (needUPM) {
        let handleUPM = () => {
            try {
                let pageAllowList = JSON.parse(getLocal('pageAllowList'))
                let isAllow =
                    pageAllowList.filter((item) => {
                        return to.path.indexOf(item.name) > -1
                    }).length > 0
                console.log(isAllow)

                if (!isAllow) {
                    // 将没有权限的路由路径放到url上，并且将页面跳转到401
                    $store.commit('setPermission', 'no')
                    next()
                    // return location.replace(url + '/onepeace/401')
                } else {
                    $store.commit('setPermission', 'yes')
                    next()
                }
            } catch (e) {
                if (!isTrue(getLocal('pageAllowList'))) {
                    $store
                        .dispatch('getAllowPage')
                        .then(() => {
                            handleUPM()
                        })
                        .catch((e) => {
                            console.log(e)
                        })
                } else {
                    return location.replace(url + '/onepeace/500')
                }
            }
        }
        handleUPM()
    } else {
        $store.commit('setPermission', 'yes')
        next()
    }
    // ------UPM逻辑完-------
    // let cityRouteAllowList = ['CityDiagnosisWeek', 'CityDiagnosisIndex']
    // if (cityRouteAllowList.includes(to.name)) {
    //   let url = location.origin + '/onepeace/401'
    //   let allowListName = `${to.name}_ALLOW_LIST`
    //   let isAllow = $CONST[allowListName].includes(getCookie('SSO_AS_UID'))
    //   if (!isAllow) {
    //     return location.replace(url)
    //   } else {
    //     next()
    //   }
    //   // next({ replace: true, name: '401' })
    // } else {
    //   next()
    // }
    // dinlt_gaia 登陆拦截器
    // store.dispatch('checkGaiaStatus')
    // function checkStatus(response) {
    //   if (response.status >= 200 && response.status < 300) {
    //     const username = Cookies.get('SSO_AS_UID')
    //     store.commit('SET_USERNAME', username)
    //     notOk(response.data)
    //   } else {
    //     const error = new Error(response.statusText)
    //     error.response = response
    //     throw error
    //   }
    //   return response.data
    // }
    // function notOk(res) {
    //   if (res && res.errno) {
    //     if (res.errno === 101 && res.redirect) {
    //       // token失效重新登陆
    //       return location.replace(res.redirect)
    //     }
    //     checkError(res.errmsg)
    //   } else if (!res) {
    //     // 什么都不返回的情况
    //     checkError('未知错误，请求异常')
    //   }
    // }
    // // 处理请求中断
    // if (to.fullPath.indexOf('link2Frame') > -1) {
    //   return
    // }
    // Vue.prototype.$cancels.forEach((cancel) => {
    //   cancel()
    // })
    // Vue.prototype.$cancels = []
    // // 404页面
    // if (to.name === 'error_404') {
    //   next()
    //   return
    // }
    // // 不需要登录认证的路由
    // if (to.meta.hasOwnProperty('noLoginIdentify') && to.meta.noLoginIdentify) {
    //   next()
    //   return
    // }
    // // 验证是否登陆
    // // let ticket = getCookie('user-fingerprint-water-mark')
    // const token = getToken()
    // if (!token && to.name !== LOGIN_PAGE_ROUTE_NAME) {
    //   // 未登录且要跳转的页面不是登录页
    //   next({
    //     name: LOGIN_PAGE_ROUTE_NAME, // 跳转到登录页
    //   })
    // } else if (!token && to.name === LOGIN_PAGE_ROUTE_NAME) {
    //   // 未登陆且要跳转的页面是登录页
    //   next() // 跳转
    // } else if (token && to.name === LOGIN_PAGE_ROUTE_NAME) {
    //   // 已登录且要跳转的页面是登录页
    //   next({
    //     name: homeRouterName, // 跳转到homeName页
    //   })
    // } else {
    //   if ($store.state.user.hasGetInfo) {
    //     linkTo(to, $store.state.user.access, next)
    //   } else {
    //     $store
    //       .dispatch('getUserInfo')
    //       .then((user) => {
    //         linkTo(to, user.access, next)
    //       })
    //       .catch(() => {
    //         setToken('')
    //         next({
    //           name: LOGIN_PAGE_ROUTE_NAME,
    //         })
    //       })
    //   }
    // }
})

router.beforeResolve((routeTo, routeFrom, next) => {
    if (routeFrom.name) {
        NProgress.start()
    }
    next()
})

router.afterEach((to) => {
    NProgress.done()
    setTitle(to, router.app)
    // 将内容部分置顶
    let dot = document.getElementsByClassName('page-content')[0] || window
    dot.scroll({
        top: 0,
        left: 0,
    })
})

export default router